package com.minxi.jsp.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "WebBaseServlet")
public class WebBaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String methodName = req.getParameter("method");//获取到表单提交的方法名，如login
        Class clazz = this.getClass();//获取到执行方法的类，一般是servlet的类，通过继承本类，拿到调用的方法执行(获取字节码对象)
        Method method = null;
        try {
            if(null != methodName && !"".equals(methodName.trim())) {//判断是否拿到方法名
                //getMethod方法返回一个 Method 对象，它反映此 Class 对象所表示的类或接口的指定公共成员方法
                //需传入方法名和参数
                method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                //对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
                //需传入obj - 从中调用底层方法的对象、args - 用于方法调用的参数
                //invoke方法返回值是一个Object，需强转成字符串
                String path = (String) method.invoke(this, req, resp);
                if (null != path) {
                    req.getRequestDispatcher(path).forward(req, resp);//根据path路径执行到跳转的页面
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

